﻿
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NetMicro.AutoMapper;
using NetMicro.Cache;
using NetMicro.Core.DynamicWebApiController.Extensions;
using NetMicro.Core.Json;
using NetMicro.Core.Snowflake;
using NetMicro.HttpClient.Extensions;
using NetMicro.JwtBearer;
using NetMicro.Nacos;
using NetMicro.Swagger.Extensions;
using NetMicro.Trace;
using NetMicro.Validations;
using NetMicro.Webs.MvcBuilderExtend;

namespace NetMicro.Host
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加WebHost
        /// </summary>
        /// <param name="services"></param>
        /// <param name="serviceCollectionOptions"></param>
        /// <param name="env">环境</param>
        /// <param name="cfg"></param>
        /// <returns></returns>
        public static IServiceCollection AddWebHost(this IServiceCollection services, ServiceCollectionOptions serviceCollectionOptions, IHostEnvironment env, IConfiguration cfg)
        {
            serviceCollectionOptions = serviceCollectionOptions ?? new ServiceCollectionOptions();

            services.AddSingleton(serviceCollectionOptions);

            //注册控制器|自定义json输出|验证
            services.AddControllers(serviceCollectionOptions.MvcOptions)
                    .AddDynamicApiControllers()
                    .AddDynamicApiControllersAsServices()
                    .AddCustomNewtonsoftJson(serviceCollectionOptions.CustomNewtonsoftJsonConfig)
                    .AddValidators();

            //配置可以同步请求读取流数据
            services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true).Configure<IISServerOptions>(x => x.AllowSynchronousIO = true);

            //添加HttpClient相关
            services.AddHttpClientExtend(serviceCollectionOptions.HttpClientService);

            //注入swagger
            services.AddSwaggers();
            //Redis缓存
            services.AddCacheWithRedis(cfg);

            //雪花算法
            services.AddSnowflake(cfg);

            //注册log
            services.AddLog();
            //注册中心
            if (serviceCollectionOptions.UseNacos)
                services.AddServiceDiscovery(cfg);
            //json
            services.AddNewtonsoftJson();
            //automapper
            services.AddMapper();

            if (serviceCollectionOptions.UseJwt)
                services.AddJwt();

            return services;
        }
    }
}
